package com.jsj.bs.controller;

import com.github.pagehelper.PageInfo;
import com.jsj.bs.pojo.*;
import com.jsj.bs.service.TbGaipaiService;
import com.jsj.bs.service.TbLeaderService;
import com.jsj.bs.service.TbOrderService;
import com.jsj.bs.service.TbUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 报修单表(TbOrder)表控制层
 *
 * @author makejava
 * @since 2020-01-06 15:23:40
 */
@Controller
@RequestMapping("/tbOrder")
public class TbOrderController {

    private static final Logger LOGGER = LogManager.getLogger(TbOrderController.class);

    /**
     * 服务对象
     */
    @Autowired
    private TbOrderService tbOrderService;
    @Autowired
    private TbUserService tbUserService;
    @Autowired
    private TbLeaderService tbLeaderService;
    @Autowired
    private TbGaipaiService tbGaipaiService;
    /**
     * 返回的结果集 自定义
     */
    private static final Result resultMsg = new Result();

    /**
     * 前台通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping(value = "/selectOne/{id}", method = RequestMethod.GET)
    @ResponseBody
    public TbOrder selectOne(@PathVariable("id") int id) {
        LOGGER.info("============前台通过主键查询单条数据======================" + id);
        LOGGER.info(tbOrderService.queryById(id));
        return tbOrderService.queryById(id);
    }


    /**
     * 前台展示页查询多条数据
     *
     * @param page     页码
     * @param pageSize 页大小
     * @param tbOrder  实体
     * @return PageInfo<TbOrder> 分页数据集合
     */
    @RequestMapping(value = "/searchAll", method = RequestMethod.GET)
    @ResponseBody
    public PageInfo<TbOrder> searchAll(@RequestParam(value = "page", defaultValue = "1") int page,
                                       @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                       TbOrder tbOrder,HttpSession session) {
        //获取当前账户
        String account = (String) session.getAttribute("account");
        TbUser tbUser = tbUserService.queryById(account);
        tbOrder.setUserId(tbUser.getUserId());
        LOGGER.info(tbOrder + "====前台展示页查询多条数据=====" + page + "====" + pageSize + "=========" +
            tbOrderService.queryAll(page, pageSize, tbOrder));
        return tbOrderService.queryAll(page, pageSize, tbOrder);
    }
    /**
     * 更新数据
     *
     * @param tbOrder
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Result update(TbOrder tbOrder) {

        LOGGER.info(tbOrder + "+=============update===========+" + tbOrderService.update(tbOrder));
        Boolean result = tbOrderService.update(tbOrder);
        if (result) {
            LOGGER.info("======操作成功=========");
            resultMsg.setFlag(true);
            resultMsg.setMsg("操作成功");
        } else {
            LOGGER.info("======操作失败=========");
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }
    /**
     * 用户管理 删除数据
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/userDeleteOrder", method = RequestMethod.GET)
    @ResponseBody
    public Result userDeleteOrder(Integer orderId) {

        LOGGER.info("+=============userDeleteOrder===========+" + orderId);
        Boolean result = tbOrderService.deleteById(orderId);
        if (result) {
            LOGGER.info("======操作成功=========");
            resultMsg.setFlag(true);
            resultMsg.setMsg("操作成功");
        } else {
            LOGGER.info("======操作失败=========");
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }



    /**
     * 前台添加报修单
     *
     * @param tbOrder 报修单
     * @param file1   文件1
     * @param file2   文件2
     * @param model   莫得
     * @param request 请求
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public String addOrder(TbOrder tbOrder, MultipartFile file1, MultipartFile file2, Model model,
                           HttpServletRequest request, HttpSession session) throws IOException {
        LOGGER.info(tbOrder + "+============addOrder============+");
        //获取当前账户
        String account = (String) session.getAttribute("account");
        TbUser tbUser = tbUserService.queryById(account);
        tbOrder.setUserId(tbUser.getUserId());
        String filename1 = null;
        String filename2 = null;
        //设置图片上传路径
        String path = request.getSession().getServletContext().getRealPath("/upload");
        LOGGER.info("========path===========" + path.toString());
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取源文件名
        filename1 = file1.getOriginalFilename();
        filename2 = file2.getOriginalFilename();
        //完成文件上传
        if (!filename1.equals("")) {
            //把文件的的名称设置成唯一值：uuid
            filename1 = UUID.randomUUID().toString().replace("-", "") + "_" + filename1;
            //将图片保存
            file1.transferTo(new File("F:/upload/" + filename1));
            //添加路径到数据库
            tbOrder.setOrderImg1(filename1);
        }
        if (!filename2.equals("")) {
            //把文件的的名称设置成唯一值：uuid
            filename2 = UUID.randomUUID().toString().replace("-", "") + "_" + filename2;
            //将图片保存
            file2.transferTo(new File("F:/upload/" + filename2));
            //添加路径到数据库
            tbOrder.setOrderImg2(filename2);
        }
        //添加时间
        Date date = new Date();
        tbOrder.setAddTime(date);
        TbOrder addOrder = tbOrderService.insert(tbOrder);
        LOGGER.info(addOrder + "+=======前台添加报修单=====addOrder=Controller===========+");
        model.addAttribute("msgorder", "success");
        return "userpage-2";
    }


    /**
     * 前台查询多条数据
     *
     * @param page     页码
     * @param pageSize 页大小
     * @param leaderId 负责人id
     * @return PageInfo<TbOrder> 分页数据集合
     */
    @RequestMapping(value = "/searchByLId", method = RequestMethod.GET)
    @ResponseBody
    public PageInfo<TbOrder> searchByLId(@RequestParam(value = "page", defaultValue = "1") int page,
                                         @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                         @RequestParam("leaderId") int leaderId) {
        LOGGER.info("====负责人id=========+" + leaderId);
        TbOrder tbOrder = new TbOrder();
        tbOrder.setLeaderId(leaderId);
        LOGGER.info(tbOrder + "====前台查询多条数据=====" + page + "====" + pageSize + "=========" +
            tbOrderService.queryAll(page, pageSize, tbOrder));
        return tbOrderService.queryAll(page, pageSize, tbOrder);
    }
    /**
     * 负责人管理 根据id更新报修单状态和状态详情
     *
     * @param orderId
     * @param statu
     * @param statuDesc
     * @return
     */
    @RequestMapping(value = "/updateDesc", method = RequestMethod.POST)
    @ResponseBody
    public Result updateDesc(@RequestParam("orderId") Integer orderId, @RequestParam("statu") String statu,
                             @RequestParam("statuDesc") String statuDesc) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(orderId);
        tbOrder.setStatu(statu);
        tbOrder.setStatuDesc(statuDesc);
        LOGGER.info(tbOrder + "+=====前台 根据id更新报修单状态和状态详情========updateDesc===========+" +
            tbOrderService.update(tbOrder));
        Boolean result = tbOrderService.update(tbOrder);
        if (result) {
            LOGGER.info("======操作成功=========");
            resultMsg.setFlag(true);
            resultMsg.setMsg("操作成功");
        } else {
            LOGGER.info("======操作失败=========");
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }
    /**
     * 后台展示数据
     *
     * @param page
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping(value = "searchOrders", method = RequestMethod.GET)
    public String searchOrders(@RequestParam(value = "page", defaultValue = "1") int page,
                               @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                               Model model) {
        LOGGER.info("=========" + page + "====" + pageSize + "=========");
        PageInfo<TbOrder> tbOrderPageInfos = tbOrderService.queryAllHT(page, pageSize);
        LOGGER.info("======后台展示数据==========" + tbOrderPageInfos);
        model.addAttribute("tbOrderPageInfos", tbOrderPageInfos);
        return "baoxiu-manager";
    }

    /**
     * 后台查询单条数据
     *
     * @param tbOrderId 主键
     * @return 单条数据
     */
    @RequestMapping(value = "/selectTbOrder", method = RequestMethod.GET)
    public String selectTbOrder(int tbOrderId, int type, Model model) {
        LOGGER.info("=============后台查询单条数据=====================" + tbOrderId);
        LOGGER.info(tbOrderService.queryById(tbOrderId));
        model.addAttribute("tbOrder", tbOrderService.queryById(tbOrderId));
        //type等于1 跳转详情页面  type等于2跳转设置报修状态页面
        if (type == 1) {
            return "detailsorder-page";
        } else {
            return "setstatu-page";
        }
    }

    /**
     * 后台 根据id更新报修单状态和状态详情  已改
     *
     * @param orderId
     * @param statu
     * @param statuDesc
     * @return
     */
    @RequestMapping(value = "/updateStatu", method = RequestMethod.POST)
    @ResponseBody
    public Result updateStatu(@RequestParam("orderId") Integer orderId, @RequestParam("statu") String statu,
                              @RequestParam("statuDesc") String statuDesc) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(orderId);
        tbOrder.setStatu(statu);
        tbOrder.setStatuDesc(statuDesc);
        LOGGER.info(tbOrder + "+=====后台 根据id更新报修单状态和状态详情========updateDesc===========+" +
            tbOrderService.update(tbOrder));
        Boolean result = tbOrderService.update(tbOrder);
        if (result) {
            LOGGER.info("======操作成功=========");
            resultMsg.setFlag(true);
            resultMsg.setMsg("操作成功");
        } else {
            LOGGER.info("======操作失败=========");
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }

    /**
     * 后台 根据id冻结报修单(为保证数据库完整  这里进行对isDeleted属性的更改进行操作)  已改
     *
     * @param orderId
     * @param isDeleted
     * @return
     */
    @RequestMapping(value = "/DongJieTbOrder", method = RequestMethod.GET)
    @ResponseBody
    public Result DongJieTbOrder(Integer orderId, Boolean isDeleted) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(orderId);
        tbOrder.setIsDeleted(!isDeleted);
        LOGGER.info(tbOrder + "+=====后台 根据id冻结报修单========updateDesc===========+" + tbOrderService.update(tbOrder));
        Boolean result = tbOrderService.update(tbOrder);
        if (result) {
            LOGGER.info("======操作成功=========");
            resultMsg.setFlag(true);
            resultMsg.setMsg("操作成功");
        } else {
            LOGGER.info("======操作失败=========");
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }

    /**
     * 后台 根据id删除报修单  已改
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/DeleteOrder", method = RequestMethod.GET)
    @ResponseBody
    public Result DeleteOrder(Integer orderId) {
        LOGGER.info("+=====后台 根据id删除报修单========DeleteOrder===========+" + orderId);
        List<TbGaipai> tbGaipaiList = tbGaipaiService.queryByorderId(orderId);
        LOGGER.info("==tbOrderList==大小=" + tbGaipaiList.size());
        Boolean aBoolean = null;
        if(tbGaipaiList.size()>0){
            for (TbGaipai tbGaipai : tbGaipaiList) {
                aBoolean = tbGaipaiService.deleteById(tbGaipai.getGaipaiId());
                LOGGER.info(aBoolean+"==tbGaipaiList==删除报修单先删除改派单=" + tbGaipai);
            }
        }
        if (aBoolean ==null){
            Boolean result = tbOrderService.deleteById(orderId);
            if (result) {
                LOGGER.info("======操作成功=========");
                resultMsg.setFlag(true);
                resultMsg.setMsg("操作成功");
            } else {
                LOGGER.info("======操作失败=========");
                resultMsg.setFlag(false);
                resultMsg.setMsg("操作失败");
            }
        }else if (aBoolean) {
            Boolean result = tbOrderService.deleteById(orderId);
            if (result) {
                LOGGER.info("======操作成功=========");
                resultMsg.setFlag(true);
                resultMsg.setMsg("操作成功");
            } else {
                LOGGER.info("======操作失败=========");
                resultMsg.setFlag(false);
                resultMsg.setMsg("操作失败");
            }
        } else {
            LOGGER.info("======操作失败=========");
            resultMsg.setFlag(false);
            resultMsg.setMsg("操作失败");
        }
        return resultMsg;
    }

    /**
     * 后台  跳转指定维修负责人页面
     *
     * @param orderId
     * @param model
     * @return
     */
    @RequestMapping(value = "/selectLeader", method = RequestMethod.GET)
    public String selectLeader(Integer orderId, Model model) {
        //根据报修单id查询报修单  然后根据报修单是否存在
        TbOrder tbOrder = tbOrderService.queryById(orderId);
        if (tbOrder != null) {
            //查询所有的维修负责人
            List<TbLeader> tbLeaders = tbLeaderService.searchLeaders();
            model.addAttribute("tbOrder", tbOrder);
            model.addAttribute("tbLeaders", tbLeaders);
            return "zdleader-page";
        }
        return "error";
    }

    /**
     * 后台 根据id指定维修负责人
     *
     * @param orderId
     * @param leaderId
     * @return
     */
    @RequestMapping(value = "/setLeaderId", method = RequestMethod.GET)
    public String setLeaderId(Integer orderId, Integer leaderId, Model model) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(orderId);
        tbOrder.setLeaderId(leaderId);
        tbOrder.setStatu("已指派");
        LOGGER.info("+=====后台 根据id指定维修负责人===========+" + tbOrderService.update(tbOrder));
        Boolean aBoolean = tbOrderService.update(tbOrder);
        if (aBoolean) {
            model.addAttribute("StatusMsg", 1);
            return "updateresult";
        } else {
            model.addAttribute("StatusMsg", 0);
            return "updateresult";
        }
    }
}